package book;

import constant.Constant;
import utils.AnalyzingBook;

import java.io.IOException;
import java.security.PublicKey;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;
import book.PairOfUserIdAndBookId;
import user.NormalUser;
public class Library {

    //存储书籍的数组
    public Book[] books;

    //记录当前图书 有效的本数
    public int bookCount;

    AnalyzingBook analyzingBook =  new AnalyzingBook();

    public PairOfUserIdAndBookId pairOfUserIdAndBookId;
    private static Library library;

    public Scanner scanner;

    public NormalUser normalUser;

    public static Library getLibrary () {
        if (library == null) {
            library = new Library();
        }
        return library;
    }

    public Library() {
        //读
        loadAllBook();
    }

    public void loadBorrowedBook() {

    }


    private void loadAllBook() {
        try {
            //1.读取文件内容
            Book[] allBook = analyzingBook.loadObject(Constant.ALL_BOOKS_FILE_NAME);

            //默认大小分配为5
            books = new Book[Constant.CAPACITY];

            //2.判断读取的书籍是否为空
            if (allBook == null){
                bookCount = 0;
            }else {
                //3.判断读取的书籍长度 是否 大于默认的长度
                if (allBook.length > books.length){
                    //3.1 如果读取的书籍长度大于默认的长度 将重新分配数组内存大小
                    books = new Book[allBook.length];
                }

                //3.2 将读取到的数组元素进行赋值
                for (int i = 0; i < allBook.length; i++) {
                    books[i] = allBook[i];
                }

                //4.修改有效的书籍本数
                bookCount = allBook.length;;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //将有效的书籍 存储图书到文件中
    private void storeBook() {
        try {
            analyzingBook.storeObject(books,Constant.ALL_BOOKS_FILE_NAME);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //共用的方法
    public void searchBook() {

    }

    public void displayBook() {
        System.out.println("显示图书");
        loadAllBook();

        for (int i = 0; i < bookCount; i++) {
            System.out.println(books[i]);
        }

    }

    public void exit() {
        System.out.println("退出系统");
        System.exit(0);
    }


    //------------------------------------------
    public void addBook(Book book) {
        System.out.println("Libary类addBook方法执行了");

        if(bookCount >= books.length) {
            System.out.println("图书馆已满，无法上架图书");
            //扩容的 TODO 如果扩容了 下面就不要进行return了
            return;
        }
        books[bookCount] = book;
        if(bookCount == 0) {
            book.setISBN(1);
        }else {
            Book bookLast = books[bookCount-1];
            book.setISBN(bookLast.getISBN()+1);
        }
        bookCount++;

        storeBook();

        System.out.println("图书上架成功！！ 图书的名称是："+book.getTitle());
    }

    public void addBook1(Book book) {
        if (bookCount >= books.length) {
            System.out.println("图书馆已满，无法上架图书");
            return;
        }

        books[bookCount] = book;
        bookCount++;
        book.setISBN(bookCount);

        storeBook();

        System.out.println("图书上架成功！图书的名称是：" + book.getTitle());




//        if(bookCount >= books.length) {
//            System.out.println("图书馆已满，无法上架图书");
//            //扩容的 TODO 如果扩容了 下面就不要进行return了
//            return;
//        }
//        //book.setBookId(bookCount+1);
//        books[bookCount] = book;
//
//        Book bookLast = books[bookCount-1];
//
//        bookCount++;
//        book.setISBN(bookLast.getISBN()+1);
//
//        //a+1  a++
//        storeBook();
//
//        System.out.println("图书上架成功！！ 图书的名称是："+book.getTitle());

    }


    public Book searchById(int ISBN) {
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if (book.getISBN() == ISBN) {
                return book;
            }
        }
        return null;
    }



    public void updateBook(Book book) {
        int ISBN = book.getISBN();
        int index = searchByIdReturnIndex(ISBN);

        if (index == -1) {
            System.out.println("没有你要更新的图书，当前书籍的ISBN码：" + ISBN);
            return;
        }

        books[index] = book;

        storeBook();

        System.out.println("书籍已更新，更新后的书籍为：" + books[index]);

    }

    public int searchByIdReturnIndex(int ISBN) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if (book.getISBN() == ISBN) {
                return i;
            }
        }
        return -1;
    }

    //下架图书
    public void removeBook(int ISBN) {
        int index = searchByIdReturnIndex(ISBN);
        if (index == -1) {
            System.out.println("没有你要删除的书籍");
            return;
        }

        for (int i = index; i < bookCount - 1; i++) {
            books[i] = books[i+1];
        }

        bookCount--;

        books[bookCount] = null;

        storeBook();


    }

    public void borrowCount() {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            System.out.println("书籍:" + book.getTitle() + " 借阅了" + book.getBorrowedCount() + "次！");
        }
    }

    public void generateBook(int n) {
        loadAllBook();

        Book[] tmp = new Book[bookCount];
        for (int i = 0; i < bookCount; i++) {
            tmp[i] = books[i];
        }

        Arrays.sort(tmp);

        Book[] generateBooks = new Book[n];

        for (int i = 0; i < n; i++) {
            generateBooks[i] = tmp[i];
        }

        System.out.println("最受欢迎的书籍：");
        for (int i = 0; i < generateBooks.length; i++) {
            Book book = generateBooks[i];
            System.out.println("书籍ISBN码：" + book.getISBN() + "  书名为：" + book.getTitle() +
                    "  作者为：" + book.getAuthor() + "  借阅次数为：" + book.getBorrowedCount());
        }


    }

    public void checkInventoryStatus() {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];

            String isBorrowed = "未借出";

            if (book.isBorrowed()) {
                isBorrowed = "已借出";
            }
            System.out.println("书籍： " + book.getTitle() + isBorrowed);
        }
    }

    public void checkRemoveOldBooks() {
        loadAllBook();
        // 获取当前时间戳
        long currentTimestamp = System.currentTimeMillis();

        // 将当前时间戳转换为 LocalDate
//        LocalDate currentDate = Instant.ofEpochMilli(currentTimestamp)
//                .atZone(ZoneId.systemDefault())
//                .toLocalDate();
        LocalDateTime currentDate = Instant.ofEpochMilli(currentTimestamp).atZone(ZoneId.systemDefault()).toLocalDateTime();


        boolean flg = false;
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            //获取当前书籍的上架时间
            LocalDateTime specifiedDate = book.getShelfDate();
            // 计算两个日期之间的差值（以年为单位）
            long yearsBetween = ChronoUnit.YEARS.between(specifiedDate, currentDate);
            if(yearsBetween >= 1) {
                System.out.print("图书 " + book.getTitle() + " 已经上架超过一年，是否移除？ (y/n)：");
                scanner.nextLine();
                String response = scanner.nextLine();
                //scanner.nextLine();
                if (response.equalsIgnoreCase("y")) {
                    //确认删除调用remove方法进行删除
                    //应该拿书籍的 ID
                    removeBook(book.getISBN());
                    i--;  // 因为后面的书已经向前移动，所以要重新检查当前索引位置
                }
                flg = true;
            }
        }
        if(!flg) {
            System.out.println("没有上架超过一年的图书！");
        }

        storeBook();

    }


    public void borrowBook(int ISBN) {
        loadAllBook();
        Book book = searchById(ISBN);
        book.setBorrowed(true);

        book.incrementBorrowCount();

        storeBook();
    }

    public void returnBook(int ISBN) {
        loadAllBook();

        Book book = searchById(ISBN);
        book.setBorrowed(false);

        book.decreaseBorrowCount();

        storeBook();
    }


}
